package com.sys.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sys.dto.AbilityCurveData;
import com.sys.dto.CheckInRequest;
import com.sys.dto.DailyProgress;
import com.sys.dto.DomainCompletionStats;
import com.sys.dto.MultiDomainCurveData;
import com.sys.entity.BizTaskLog;
import com.sys.service.GrowthBoxService;
import com.sys.service.ProgressService;
import com.sys.service.TaskLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "打卡与进度管理")
@RestController
@RequestMapping("/api")
public class ProgressController {

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private ProgressService progressService;

    @Autowired
    private GrowthBoxService growthBoxService;
    
    @Autowired
    private ObjectMapper objectMapper;

    @ApiOperation(value = "任务打卡（带照片上传）", notes = "支持上传照片的完整打卡接口")
    @PostMapping(value = "/checkIn", consumes = "multipart/form-data")
    public BizTaskLog checkIn(
            @ApiParam(value = "打卡数据（JSON字符串）", required = true, example = "{\"userId\":1,\"taskId\":1,\"score\":85,\"remarks\":\"今天完成很好\"}")
            @RequestParam("checkInData") String checkInDataJson,
            @ApiParam(value = "打卡照片（可选）")
            @RequestPart(value = "photoFile", required = false) MultipartFile photoFile) throws Exception {
        
        // 解析 JSON 字符串为对象
        CheckInRequest checkInRequest = objectMapper.readValue(checkInDataJson, CheckInRequest.class);
        
        return taskLogService.checkIn(checkInRequest, photoFile);
    }

    @ApiOperation(value = "任务打卡（简化版-适用于Swagger测试）", notes = "分开传递参数，方便在Swagger中测试")
    @PostMapping("/checkIn/simple")
    public BizTaskLog checkInSimple(
            @ApiParam(value = "用户ID", required = true, example = "1") @RequestParam Long userId,
            @ApiParam(value = "任务ID", required = true, example = "1") @RequestParam Long taskId,
            @ApiParam(value = "计划项ID（可选）", example = "5") @RequestParam(required = false) Long planItemId,
            @ApiParam(value = "完成评分（0-100）", example = "85") @RequestParam(required = false) Integer score,
            @ApiParam(value = "备注说明", example = "今天完成很好") @RequestParam(required = false) String remarks,
            @ApiParam(value = "打卡照片（可选）") @RequestPart(value = "photoFile", required = false) MultipartFile photoFile) {
        
        CheckInRequest request = new CheckInRequest();
        request.setUserId(userId);
        request.setTaskId(taskId);
        request.setPlanItemId(planItemId);
        request.setScore(score);
        request.setRemarks(remarks);
        
        return taskLogService.checkIn(request, photoFile);
    }

    @PostMapping("/task/markMastered")
    public Map<String, Object> markMastered(@RequestParam Long userId, @RequestParam Long taskId) {
        growthBoxService.addTaskToGrowthBox(userId, taskId, null);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("msg", "已收纳进成长盒");
        return response;
    }

    @GetMapping("/progress/daily")
    public DailyProgress getDailyProgress(@RequestParam Long userId) {
        return progressService.getDailyProgress(userId);
    }

    @GetMapping("/progress/curve")
    public AbilityCurveData getAbilityCurve(@RequestParam Long userId,
            @RequestParam String domain,
            @RequestParam String timeRange) {
        return progressService.getAbilityCurve(userId, domain, timeRange);
    }

    @GetMapping("/progress/history")
    public List<Map<String, Object>> getHistory(@RequestParam Long userId, 
            @RequestParam String startDate, 
            @RequestParam String endDate) {
        return progressService.getHistory(userId, startDate, endDate);
    }

    @GetMapping("/progress/multiDomainCurve")
    public MultiDomainCurveData getMultiDomainCurve(@RequestParam Long userId, 
            @RequestParam String startDate, 
            @RequestParam String endDate) {
        return progressService.getMultiDomainCurve(userId, startDate, endDate);
    }

    @GetMapping("/progress/domainStats")
    public List<DomainCompletionStats> getDomainStats(@RequestParam Long userId, 
            @RequestParam String startDate, 
            @RequestParam String endDate) {
        return progressService.getDomainCompletionStats(userId, startDate, endDate);
    }
}